package com.jh.jingfei.bottom_bar;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.StyleRes;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.animation.AnimationSet;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.jh.jingfei.R;
import com.jh.jingfei.utils.DensityUtil;

/**
 * @author lxb
 * Created by sxb on 2017/7/19.
 */

public class BottomNavigationTab extends FrameLayout {

    private FrameLayout mNavIconContainer;
    private ImageView mIconIv;
    private TextView mTitleTv;
    private TextView mBadgeTv;

    // 未选中状态
    private Drawable mInactiveIcon;

    // 选中状态
    private Drawable mIcon;

    // 未选中状态
    private int mTitleColor;
    private int mTitleSize = 16;
//    private int mInactiveTitleSize = 16;

    // 选中状态
    private int mTitleInactiveColor;

    private int mBadge;
    private String mTitle;
    private boolean isActive = false;

    public BottomNavigationTab(@NonNull Context context) {
        this(context, null);
    }

    public BottomNavigationTab(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public BottomNavigationTab(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public BottomNavigationTab(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.BottomNavTab, 0, 0);

        if (arr != null) {
            mBadge = arr.getInteger(R.styleable.BottomNavTab_badge, 0);
            mTitle = arr.getString(R.styleable.BottomNavTab_title);
            mIcon = arr.getDrawable(R.styleable.BottomNavTab_active_icon);
            mInactiveIcon = arr.getDrawable(R.styleable.BottomNavTab_inactive_icon);

            isActive = arr.getBoolean(R.styleable.BottomNavTab_active, false);

            mTitleColor = arr.getColor(R.styleable.BottomNavTab_title_color, getContext().getResources().getColor(R.color.colorPrimary));
            mTitleInactiveColor = arr.getColor(R.styleable.BottomNavTab_title_inactive_color, getContext().getResources().getColor(R.color.colorTxtInactive));

            arr.recycle();
        } else {
            mBadge = 0;
            mTitle = "";
            isActive = false;
            mTitleColor = getContext().getResources().getColor(R.color.colorPrimary);
            mTitleInactiveColor = getContext().getResources().getColor(R.color.colorTxtInactive);
        }

        createNavigationIconContainer();
        createTitleTv();

        if (isActive) {
            active();
        } else {
            inactive();
        }
    }

    private void createNavigationIconContainer() {
        if (mNavIconContainer == null) {
            mNavIconContainer = new FrameLayout(getContext());
            int w = getContext().getResources().getDimensionPixelOffset(R.dimen.fixed_icon_badge_grid_width);
            int h = getContext().getResources().getDimensionPixelOffset(R.dimen.fixed_icon_badge_grid_height);
            LayoutParams lp = new LayoutParams(w, h);
            lp.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;

            mNavIconContainer.setLayoutParams(lp);

            if (mIconIv == null) {
                mIconIv = new ImageView(getContext());

                int ivdph = getContext().getResources().getDimensionPixelOffset(R.dimen.fixed_icon_grid);
                LayoutParams ivIp = new LayoutParams(ivdph, ivdph);

                ivIp.gravity = Gravity.CENTER;

                mIconIv.setLayoutParams(ivIp);
                mIconIv.setScaleType(ImageView.ScaleType.FIT_XY);

                mNavIconContainer.addView(mIconIv);
            }

            if (mBadgeTv == null) {
                mBadgeTv = new TextView(getContext());
                LayoutParams tvIp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                tvIp.gravity = Gravity.TOP | Gravity.END;
                tvIp.topMargin = DensityUtil.dp2px(getContext(), 2);
                mBadgeTv.setLayoutParams(tvIp);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mBadgeTv.setTextAppearance(R.style.BadgeText);
                }

                int leftRight = DensityUtil.dp2px(getContext(), 5);
                int topBottom = DensityUtil.dp2px(getContext(), 1);
                mBadgeTv.setPadding(leftRight, topBottom, leftRight, topBottom);
                mBadgeTv.setIncludeFontPadding(false);

                mBadgeTv.setBackgroundResource(R.drawable.bottom_badge_num);
                mBadgeTv.setGravity(Gravity.CENTER);
                mBadgeTv.setTextAlignment(TEXT_ALIGNMENT_CENTER);
                mBadgeTv.setTextColor(getContext().getResources().getColor(R.color.white));
                mBadgeTv.setTextSize(12);

                if(mBadge > 0) {
                    mBadgeTv.setText("" + mBadge);
                } else {
                    mBadgeTv.setVisibility(INVISIBLE);
                }

                mNavIconContainer.addView(mBadgeTv);
            }

            this.addView(mNavIconContainer);
        }
    }

    private void createTitleTv() {
        if(mTitleTv == null) {
            mTitleTv = new TextView(getContext());
            FrameLayout.LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

            lp.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
            mTitleTv.setLayoutParams(lp);
            mTitleTv.setGravity(Gravity.CENTER);
            // includeFontPadding
            mTitleTv.setIncludeFontPadding(false);
            // android:lines="1"
            mTitleTv.setLines(1);

            if (mTitle != null && mTitle.length() > 0) {
                mTitleTv.setText(mTitle);
            }

            mTitleTv.setTextSize(mTitleSize);

            this.addView(mTitleTv);
        }
    }

    public void active() {
        isActive = true;
        if (mIcon != null) {
            mIconIv.setImageDrawable(mIcon);
        }

//        mTitleTv.setTextColor(mTitleColor);

//        mTitleTv.setScaleX(1F);
//        mTitleTv.setScaleY(1F);
//
//        mIconIv.setScaleX(1F);
//        mIconIv.setScaleY(1F);

        // 动画修改title颜色
        ValueAnimator animator = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            animator = ObjectAnimator.ofArgb(mTitleTv, "textColor", mTitleInactiveColor, mTitleColor);
        } else {
            animator = ObjectAnimator.ofInt(mTitleTv, "textColor", mTitleInactiveColor, mTitleColor);
        }

        // 动画修改 scale
        ValueAnimator animator1 = ValueAnimator.ofFloat(0.857F, 1F);
        animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float f = (Float) animation.getAnimatedValue();
                mTitleTv.setScaleX(f);
                mTitleTv.setScaleY(f);

                mIconIv.setScaleX(f);
                mIconIv.setScaleY(f);
            }
        });

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(animator, animator1);
        animatorSet.setDuration(300);
        animatorSet.start();

        int top = DensityUtil.dp2px(getContext(), 0);
        setPadding(getPaddingLeft(), top, getPaddingRight(), getPaddingBottom());
    }

    public void inactive() {
        isActive = false;
        if (mInactiveIcon != null) {
            mIconIv.setImageDrawable(mInactiveIcon);
        }

//        mTitleTv.setTextColor(mTitleInactiveColor);
//        mTitleTv.setScaleX(0.857F);
//        mTitleTv.setScaleY(0.857F);
//        mIconIv.setScaleX(0.857F);
//        mIconIv.setScaleY(0.857F);

        ValueAnimator animator = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            animator = ObjectAnimator.ofArgb(mTitleTv, "textColor", mTitleColor, mTitleInactiveColor);
        } else {
            animator = ObjectAnimator.ofInt(mTitleTv, "textColor", mTitleColor, mTitleInactiveColor);
        }

        ValueAnimator animator1 = ValueAnimator.ofFloat(1F, 0.857F);
        animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float f = (Float) animation.getAnimatedValue();
                mTitleTv.setScaleX(f);
                mTitleTv.setScaleY(f);

                mIconIv.setScaleX(f);
                mIconIv.setScaleY(f);
            }
        });

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(animator, animator1);
        animatorSet.setDuration(300);
        animatorSet.start();

        int top = DensityUtil.dp2px(getContext(), 2);
        setPadding(getPaddingLeft(), top, getPaddingRight(), getPaddingBottom());
    }

    public void setTitle(String title) {
        mTitle = title;
        mTitleTv.setText(title);
    }

    public String getTitle() {
        return mTitle;
    }

    public void setBadge(int badge) {
        mBadge = badge;
        if(badge <= 0) {
            hideBadge();
        } else {
            showBadge();
        }
    }

    private void hideBadge() {
        ValueAnimator animator1 = ValueAnimator.ofFloat(1F, 0.5F, 0F);
        animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float f = (Float) animation.getAnimatedValue();

                mBadgeTv.setScaleX(f);
                mBadgeTv.setScaleY(f);
            }
        });

        animator1.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mBadgeTv.setVisibility(GONE);
                mBadgeTv.setText("");
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        animator1.setDuration(500);
        animator1.start();
    }


    private void showBadge() {
        ValueAnimator animator1 = ValueAnimator.ofFloat(0.5F, 1F, 1.5F, 1F);
        animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float f = (Float) animation.getAnimatedValue();

                mBadgeTv.setScaleX(f);
                mBadgeTv.setScaleY(f);
            }
        });

        animator1.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mBadgeTv.setVisibility(VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mBadgeTv.setText(String.format("%d", mBadge));
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator1.setDuration(500);
        animator1.start();
    }

    public void clearBadge() {
        mBadge = 0;
        hideBadge();
    }

    public void setIconResource(@DrawableRes int resId) {
        mIcon = getContext().getResources().getDrawable(resId);
        mIconIv.setImageResource(resId);
    }

    public void setIconDrawable(@Nullable Drawable drawable) {
        mIcon = drawable;
        mIconIv.setImageDrawable(drawable);
    }

    public int getTitleColor() {
        return mTitleColor;
    }

    public void setTitleColor(@ColorInt int mTitleColor) {
        this.mTitleColor = mTitleColor;
    }

    public void setTitleColorResource(@ColorRes int mTitleColor) {
        this.mTitleColor = getContext().getResources().getColor(mTitleColor);
    }

    public int getTitleInactiveColor() {
        return mTitleInactiveColor;
    }

    public void setTitleInactiveColor(@ColorInt int mTitleInactiveColor) {
        this.mTitleInactiveColor = mTitleInactiveColor;
    }

    public void setTitleInactiveColorResource(@ColorRes int mColor) {
        this.mTitleInactiveColor = getContext().getResources().getColor(mColor);
    }
}
